<template>
  <div v-if="$route.path !== '/login'" v-show="$store.state.headers" class="header-wrapper">
    <login-page />
    <!-- 主导航栏 -->
    <header class="header" ref="headerEl">
      <div class="header-container">
        <!-- Logo区域 -->
        <div class="logo-section" @click="goHome">
          <img :src="logoSrc" alt="FURNITURA" class="logo" />
        </div>

        <!-- 导航菜单 -->
        <nav class="nav-menu">
          <nuxt-link :to="item.url" class="nav-item" :class="{ active: isActiveRoute(item.url) }"
            v-for="(item, index) in $store.state.homeMenus" :key="index">
            {{ item.title }}
          </nuxt-link>
        </nav>

        <!-- 右侧功能区 -->
        <div class="header-actions">
          <!-- 搜索模块 -->
          <div class="search-section">
            <!-- 搜索区域 -->
            <div class="search-area" @mouseenter.stop="toggleSearch" @mouseleave.stop="handleSearchLeave" @click.stop>
              <!-- 搜索按钮 -->
              <div class="search-button" :class="{ 'search-active': showSearchInput }">
                <TheIcon icon="search" class="header-icon" :class="{ 'active-icon': showSearchInput }" size="21" />
              </div>
              <!-- 搜索输入框 -->
              <div class="search-wrapper" :class="{ 'search-active': showSearchInput }">
                <div class="search-input-wrapper">
                  <span class="iconfont icon-search search-icon header-icon" @click.prevent.stop="submit"></span>
                  <input type="text" placeholder="搜索商品" v-model="search" class="search-input"
                    @keyup.enter.prevent.stop="submit" @focus="inputFocused = true" @blur="inputFocused = false"
                    ref="searchInput" />
                  <button class="close-search" @click.stop="closeSearch">×</button>
                </div>
              </div>
            </div>
          </div>

          <!-- 收藏 -->
          <nuxt-link :to="{ path: '/user/collect', query: { page_type: 2 } }" class="favorite-link">
            <TheIcon :icon="$route.path.includes('/user/collect')
              ? 'favorite-filled'
              : 'favorite'
              " class="header-icon" :class="{ 'active-icon': $route.path.includes('/user/collect') }" />
          </nuxt-link>

          <!-- 购物车 -->
          <nuxt-link to="/shoppingCart" class="cart-link" :class="{ 'has-items': $route.path === '/shoppingCart' }">
            <TheIcon icon="shopping-cart" class="header-icon"
              :class="{ 'active-icon': $route.path === '/shoppingCart' }" />
            <span class="cart-count" :class="{ 'large-count': $store.state.cartnumber > 99 }"
              v-show="$store.state.cartnumber > 0">
              {{
                $store.state.cartnumber > 99 ? "99+" : $store.state.cartnumber
              }}
            </span>
          </nuxt-link>

          <!-- 用户信息 -->
          <div class="user-info">
            <nuxt-link :to="{ path: '/user', query: { page_type: 0 } }" class="user-link" v-if="$auth.loggedIn">
              <div class="user-avatar" v-if="$auth.user.avatar">
                <img :src="$auth.user.avatar" alt="用户头像" />
              </div>
              <TheIcon icon="user" class="user-icon header-icon" v-else />
              <img src="~/assets/images/king.png" class="vip-badge"
                v-if="$auth.user.is_open_member && $auth.user.is_money_level" />
            </nuxt-link>
            <a href="javascript:void(0)" @click.prevent="showLoginModal" class="login-link" v-else>
              <TheIcon icon="user" class="user-icon header-icon" :clickable="true" />
            </a>
          </div>
        </div>
      </div>
    </header>
  </div>
</template>

<script>
import TheIcon from "~/components/TheIcon.vue";
import Logo from "~/components/Logo.vue";
import LoginPage from "~/components/LoginModal.vue";

export default {

  name: "headers",
  components: {
    TheIcon,
    Logo,
    LoginPage,
  },
  data() {
    return {
      userInfo: {},
      service_num: "",
      search: "",
      showSearchInput: false,
      inputFocused: false,
      isClosing: false, // 添加关闭状态标志位
      isScrolled: false // 追踪滚动状态
    };
  },
  computed: {
    logoSrc() {
      return require('~/assets/logo/logo-gold.png');
    },
    isLoginModalVisible() {
      return this.$store.state.showLoginModal;
    }
  },
  created() {
    if (this.$auth.loggedIn) {
      this.gainCount();
      this.service_num = this.$auth.user.service_num;
      this.$store.commit("serviceNum", this.$auth.user.service_num);
    }
  },

  mounted() {
    // 只綁定點擊事件，滾動事件由外部控制
    if (typeof window !== 'undefined') {
      window.addEventListener("click", this.handleOutsideClick);
    }


  },

  beforeDestroy() {
    if (typeof window !== 'undefined') {
      window.removeEventListener("click", this.handleOutsideClick);
    }
  },

  watch: {
    // 监听路由变化

  },

  methods: {
    // 由外部控制滾動狀態的方法
    setScrolled(isScrolled) {
      // 如果狀態沒有變化，不執行任何操作
      if (this.isScrolled === isScrolled) return;

      if (typeof document !== 'undefined' && this.$refs.headerEl) {
        if (isScrolled) {
          this.$refs.headerEl.classList.add('scrolled');
          document.body.classList.add('header-scrolled');
        } else {
          document.body.classList.remove('header-scrolled');
          this.$refs.headerEl.classList.remove('scrolled');
        }
      }

      // 更新狀態放在最後，確保DOM操作先完成
      this.isScrolled = isScrolled;
    },

    handleScroll() {
      // 獲取滾動位置
      let scrollPosition = 0;
      if (typeof window !== 'undefined') {
        scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
      }

      // 使用setScrolled方法統一處理滾動狀態和樣式
      const newScrolled = scrollPosition > 30;
      this.setScrolled(newScrolled);
    },
    showLoginModal() {
      this.$store.commit('SET_SHOW_LOGIN_MODAL', true);
    },
    goHome() {
      this.$router.push({ path: "/" });
    },
    isActiveRoute(menuUrl) {
      // 处理完整URL匹配（包含查询参数）
      const currentFullPath = this.$route.fullPath;
      if (menuUrl === currentFullPath) {
        return true;
      }

      // 处理路径匹配（不包含查询参数）
      const currentPath = this.$route.path;
      if (menuUrl === currentPath) {
        return true;
      }

      // 处理带查询参数的URL
      if (menuUrl.includes("?")) {
        const [menuPath, menuQuery] = menuUrl.split("?");
        if (currentPath === menuPath) {
          const urlParams = new URLSearchParams(menuQuery);
          const routeParams = new URLSearchParams(this.$route.query);

          // 检查所有菜单URL中的查询参数是否匹配
          for (const [key, value] of urlParams) {
            if (routeParams.get(key) !== value) {
              return false;
            }
          }
          return true;
        }
      }

      return false;
    },
    AddFavorite() {
      let url = window.location;
      let title = document.title;
      let ua = navigator.userAgent.toLowerCase();
      if (ua.indexOf("360se") > -1) {
        this.$message("由于360浏览器功能限制，请按 Ctrl+D 手动收藏！");
      } else if (ua.indexOf("msie 8") > -1) {
        window.external.AddToFavoritesBar(url, title); //IE8
      } else if (document.all) {
        try {
          window.external.addFavorite(url, title);
        } catch (e) {
          this.$message("您的瀏覽器不支持,請按 Ctrl+D 手動收藏!");
        }
      } else if (window.sidebar) {
        this.$message("您的瀏覽器不支持,請按 Ctrl+D 手動收藏!");
      } else {
        this.$message("您的瀏覽器不支持,請按 Ctrl+D 手動收藏!");
      }
    },
    gainCount: function () {
      let that = this;
      that.$axios
        .get("/cart/count", {
          params: {
            numType: 0,
          },
        })
        .then((res) => {
          that.$store.commit("cartNum", res.data.count);
        });
    },
    toggleSearch(event) {
      // 阻止事件冒泡和默认行为
      if (event) {
        event.stopPropagation();
        event.preventDefault();
      }

      // 添加标志位，防止关闭后立即触发
      if (this.isClosing) return;

      console.log('打开搜索框');
      this.showSearchInput = true;
      this.$nextTick(() => {
        if (this.$refs.searchInput) {
          this.$refs.searchInput.focus();
          this.inputFocused = true;
        }
      });
    },

    handleOutsideClick(event) {
      // 如果搜索框显示且点击区域不在搜索区域内
      if (this.showSearchInput && !event.target.closest('.search-area')) {
        this.closeSearch();
      }
    },
    handleSearchLeave(event) {
      // 阻止事件冒泡和默认行为
      if (event) {
        event.stopPropagation();
        event.preventDefault();
      }

      if (!this.inputFocused) {
        this.closeSearch();
      }
    },
    closeSearch(event) {
      // 阻止事件冒泡和默认行为
      if (event) {
        event.stopPropagation();
        event.preventDefault();
      }

      console.log('关闭搜索框');
      this.showSearchInput = false;
      this.inputFocused = false;
      this.search = "";

      // 设置关闭状态标志位，防止关闭后立即触发mouseenter
      this.isClosing = true;

      // 300ms后清除标志位，与CSS过渡动画时间一致
      setTimeout(() => {
        this.isClosing = false;
      }, 300);
    },
    submit(event) {
      // 阻止事件冒泡和默认行为
      if (event) {
        event.stopPropagation();
        event.preventDefault();
      }

      console.log('执行搜索提交方法');
      if (this.search.trim() !== "") {
        // 使用replace而不是push，避免历史堆栈问题
        this.$router.push({
          path: "/goods_search",
          query: { title: this.search.trim() },
        });
        this.search = "";
        this.showSearchInput = false;
      } else {
        this.$message.error("請輸入要搜索的内容");
      }
    },
  },
};
</script>

<style scoped lang="scss">
// 頭部圖標樣式
.header-icon {
  transition: color 0.3s ease;

  // 统一图标颜色
  stroke: $pure-white;
  fill: $pure-white;

  &:hover {
    stroke: $dark-gold;
    fill: $dark-gold;
  }

  // 激活狀態的圖標顏色
  &.active-icon {
    stroke: $dark-gold;
    fill: $dark-gold;
  }
}

.header-wrapper {
  padding-top: 80px;
}

.header {
  width: 100%;
  height: 80px;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  transition: all 0.3s ease;
  background: transparent;
  will-change: background-color, box-shadow;

  /* 滚动时的背景样式 */
  &.scrolled {
    background-color: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateZ(0);
  }

  /* 确保滚动时添加背景 */
  body.header-scrolled & {
    background-color: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateZ(0);
  }



  .header-container {
    width: 100%;
    height: 100%;
    padding: 0 min(100px, 8vw);
    margin: 0 auto;
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    align-items: center;

    .logo-section {
      display: flex;
      align-items: center;
      cursor: pointer;

      .logo {
        height: 40px;
        width: auto;
      }

      .nuxt-logo {
        height: 40px;
        width: auto;
      }

      .logo-text {
        font-size: 24px;
        font-weight: 700;
        letter-spacing: 1px;
      }
    }

    .nav-menu {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 24px;

      .nav-item {
        color: $pure-white;
        /* 使用主题变量 */
        padding: 8px 0;
        text-decoration: none;
        font-size: 1rem;
        font-weight: 500;
        position: relative;
        white-space: nowrap;
        letter-spacing: 1px;
        transition: color 0.3s ease;

        &::after {
          content: "";
          position: absolute;
          bottom: -2px;
          left: 50%;
          width: 0;
          height: 1px;
          background-color: $dark-gold;
          transition: all 0.3s ease;
          transform: translateX(-50%);
        }

        &:hover {
          color: $dark-gold;

          &::after {
            width: 100%;
          }
        }

        &.active {
          color: $dark-gold;

          &::after {
            width: 100%;
          }
        }
      }
    }

    .header-actions {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      align-items: center;
      gap: 14px;

      .search-section {
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;

        .search-area {
          display: flex;
          align-items: center;
          position: relative;
          z-index: 10;
          justify-content: flex-end;
        }

        .search-button {
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 8px;
          border-radius: 50%;
          cursor: pointer;
          transition: all 0.3s ease;
          position: relative;
          z-index: 2;
        }

        .search-wrapper {
          display: flex;
          align-items: center;
          position: absolute;
          top: -10px;
          right: 40px;
          width: 300px;
          height: 0;
          overflow: hidden;
          opacity: 0;
          transition: all 0.3s ease;
          z-index: 1000;
          transform: translateY(-10px);

          &.search-active {
            height: 60px;
            opacity: 1;
            transform: translateY(0);
          }

          .search-input-wrapper {
            display: flex;
            align-items: center;
            background: rgba(255, 255, 255, 0.95);
            border: 1px solid rgba(139, 90, 43, 0.2);
            border-radius: 8px;
            padding: 12px 16px;
            width: 100%;
            min-width: 280px;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            margin-right: 10px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);

            &:focus-within {
              border-color: $gold-light;
              box-shadow: 0 2px 12px rgba(139, 90, 43, 0.2);
            }

            .search-icon {
              margin-right: 8px;
              cursor: pointer;
              transition: all 0.3s ease;
              width: 16px;
              height: 16px;
              flex-shrink: 0;
              color: rgba(0, 0, 0, 0.3) !important;
              font-size: 18px;
              display: flex;
              align-items: center;
              justify-content: center;

              &:hover {
                scale: 1.03;
              }

              &:active {
                transform: scale(0.95);
              }
            }

            .close-search {
              background: none;
              border: none;
              color: $slate;
              font-size: 18px;
              cursor: pointer;
              padding: 0;
              margin-left: 8px;
              transition: color 0.3s ease;
              display: flex;
              align-items: center;
              justify-content: center;
              width: 20px;
              height: 20px;

              &:hover {
                color: $gold-light;
              }
            }

            .search-input {
              border: none;
              outline: none;
              background: transparent;
              flex: 1;
              font-size: 14px;
              color: $obsidian;
              font-weight: 400;
              width: 100%;

              &::placeholder {
                color: $slate;
                font-size: 14px;
              }
            }
          }
        }
      }

      .favorite-link {
        display: flex;
        align-items: center;
        justify-content: center;
        color: $pure-white;
        padding: 8px;
        border-radius: 50%;
        transition: all 0.3s ease;
        text-decoration: none;

        .icon {
          width: 24px;
          height: 24px;
          transition: all 0.3s ease;
        }
      }

      .cart-link {
        position: relative;
        display: flex;
        align-items: center;
        padding: 8px;
        border-radius: 50%;
        transition: background-color 0.3s ease;
        text-decoration: none;
      }

      .cart-count {
        position: absolute;
        top: -2px;
        right: -2px;
        background: $dark-gold;
        color: white;
        font-size: 10px;
        font-weight: 700;
        min-width: 16px;
        height: 16px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0;
        animation: cart-badge-pulse 0.3s ease-out;
        z-index: 5;
        /* 確保在最上層 */
        visibility: visible;
        /* 確保可見 */
        opacity: 1;

        // 當數量大於99時調整樣式
        &.large-count {
          min-width: 20px;
          height: 16px;
          border-radius: 8px;
          font-size: 9px;
          padding: 0 2px;
        }
      }
    }

    .user-info {

      .user-link,
      .login-link {
        display: flex;
        align-items: center;
        gap: 8px;
        color: $pure-white;
        text-decoration: none;
        padding: 8px;
        border-radius: 50%;
        transition: all 0.3s ease;

        &:hover {
          .user-icon {
            color: $dark-gold;
          }
        }

        .user-avatar {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          overflow: hidden;

          &:hover {
            border: 1px solid $dark-gold;
          }

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .user-icon {
          width: 24px;
          height: 24px;
          transition: all 0.3s ease;
        }

        .vip-badge {
          width: 16px;
          height: 16px;
          position: absolute;
          top: -2px;
          right: -2px;
        }
      }
    }
  }

}

// 响应式设计
.header-wrapper {
  padding-top: 60px;

  @media (max-width: 768px) {
    .header {
      .header-container {
        max-width: calc(100vw - 32px);
        padding: 0 16px;
        grid-template-columns: 1fr 2fr 1fr;
        gap: 10px;
      }

      .nav-menu {
        display: none;
      }

      .search-section {
        .search-wrapper {
          max-width: 200px;
          gap: 4px;

          .search-input-wrapper {
            padding: 6px 12px;

            .search-input {
              font-size: 12px;

              &::placeholder {
                font-size: 12px;
              }
            }
          }

          .search-btn {
            padding: 6px 12px;
            font-size: 12px;
          }
        }
      }

      .header-actions {
        gap: 16px;



        .user-info {
          .username {
            display: none;
          }
        }
      }
    }
  }

  // 保持原有的动画效果
  @keyframes notification-pulse {
    0% {
      transform: scale(1);
    }

    50% {
      transform: scale(1.1);
    }

    100% {
      transform: scale(1);
    }
  }

  // 購物車徽章動畫
  @keyframes cart-badge-pulse {
    0% {
      transform: scale(0.8);
      opacity: 0.8;
    }

    50% {
      transform: scale(1.1);
      opacity: 1;
    }

    100% {
      transform: scale(1);
      opacity: 1;
    }
  }

  .notification-link {
    .notification-icon {
      animation: notification-pulse 2s infinite ease-in-out;
    }
  }
}
</style>
